package com.wuzihao.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzihao.reggie.common.BaseContext;
import com.wuzihao.reggie.entity.ShoppingCart;
import com.wuzihao.reggie.mapper.ShoppingCartMapper;
import com.wuzihao.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    ShoppingCartService shoppingCartService;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",currentId);
        //判断添加的是餐品还是套餐
        if(shoppingCart.getDishId() != null){
            //添加的是菜品
            queryWrapper.eq("dish_id",shoppingCart.getDishId());
        }else{
            //添加的是套餐
            queryWrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        //查询购物车中是否有该项菜品/套餐
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        if(one != null){
            //购物车中已有当前菜品/套餐
            Integer number = one.getNumber();
            one.setNumber(number + 1);
            shoppingCartService.updateById(one);
        }else {
            //购物车中当前没有改餐品/套餐
            //数量默认为1
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            one = shoppingCart;
        }
        return one;
    }

    @Override
    public List<ShoppingCart> listShoppingCart() {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",BaseContext.getCurrentId());
        queryWrapper.orderByAsc("create_time");

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return list;
    }

    @Override
    public void delete() {
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().eq("user_id",BaseContext.getCurrentId()));
    }
}
